from django.forms.models import model_to_dict
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from rest_framework import serializers
import datetime
from base.models import User,Role,Permission

from django.core.cache import cache
from rest_framework.permissions import BasePermission
import logging

logger = logging.getLogger("custom")

# 自定义权限
class CustomJWTPermission(BasePermission):
    def __init__(self):
        super().__init__()

    def has_permission(self, request, view):
        if check_user_permission(request.user,view.__class__.__name__):
            return True
        else:
            return False
    
# 获取用户权限
def get_user_permissions(user,refresh=True):
    if refresh:
        cache.delete(f"user_permissions_{user.id}")
    permissions_dict = cache.get(f"user_permissions_{user.id}")
    if permissions_dict:
        return permissions
    permissions = user.permissions.all()
    roles = user.roles.all()
    for role in roles:
        permissions |= role.permissions.all()
    permissions_dict = [model_to_dict(instance) for instance in permissions]
    cache.set(f"user_permissions_{user.id}",permissions_dict,3600)
    return permissions_dict

# 获取权限树
def get_permissions_tree():
    permissions = Permission.objects.filter(status=True)
    permissions_dict = [model_to_dict(instance) for instance in permissions]
    permissions_tree = list(filter(lambda permission: permission['pid'] == 0, permissions_dict))
    for permission in permissions_tree:
        permission['children'] = get_permission_childrens(permission, permissions_dict)
    return permissions_tree

# 获取权限的子权限
def get_permission_childrens(permission, permissions_dict):
    childrens = list(filter(lambda child: child['pid'] == permission['id'], permissions_dict))
    for child in childrens:
        child['children'] = get_permission_childrens(child, permissions_dict)
        if child['id'] == 3:
            child['children']
    return childrens

# 检查用户是否有权限
def check_user_permission(user, permission_name):
    if user.is_anonymous:
        return False
    permissions = get_user_permissions(user)
    for permission in permissions:
        #print(permission)
        if permission['name'] == permission_name:
            return True
    return False

# 获取用户菜单
def get_user_menu(user):
    permissions_dict = get_user_permissions(user)
    permissions_tree = list(filter(lambda permission: permission['pid'] == 0 and permission['type'] in ['menu','menu_dir'], permissions_dict))

    for permission in permissions_tree:
        permission['children'] = get_user_menu_childrens(permission, permissions_dict)
    permissions_tree = sorted(permissions_tree, key=lambda x: x['id'])
    return permissions_tree

# 获取用户菜单的子菜单
def get_user_menu_childrens(permission, permissions_dict):
    if permission['type'] != 'menu_dir':
        return []
    childrens = list(filter(lambda child: child['pid'] == permission['id'] and child['type'] in ['menu','menu_dir'], permissions_dict))
    for child in childrens:
        child['children'] = get_user_menu_childrens(child, permissions_dict)
    return childrens
      
# 自定义token验证
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    
    def validate(self, attrs):
        # self.context['request'].data 中包含了所有前端出过来的参数
        username = attrs.get("username")
        password = attrs.get("password")

        if not username or not password:
            raise serializers.ValidationError("username and password are required")
        
        user = User.objects.filter(username=username).first()
        if not user:
            raise serializers.ValidationError("user not found")

        if not user.check_password(password):
            raise serializers.ValidationError("Incorrect password")
        refresh = self.get_token(user)
        permissions = get_user_permissions(user)
        user_menu = get_user_menu(user)
        data = {
            "code":200,
            "userInfo": {
                "id": 0,
                "username": user.username,
                "nickname": user.username_show,
                "avatar": '',
                "last_login_time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "token": str(refresh.access_token),
                "refresh_token": str(refresh),
                "permissions": permissions,
                "user_menu": user_menu
            }
        }
        return data

# 创建默认用户密码
def create_default_user_password():
    user = User.objects.filter(username='admin').first()
    user.set_password('admin')
    user.save()
